package com.realm;

import com.bean.Users;
import com.bean.vo.UserVo;
import com.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

//权限管理之类也
public class KillListRealm extends AuthorizingRealm {

    @Autowired
    private UsersService usersService;

    //角色信息授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户信息
        Subject subject = SecurityUtils.getSubject();
        UserVo user = (UserVo) subject.getPrincipal();

        //设置角色
        Set<String> roles = new HashSet<>();
        roles.add(user.getRoleName());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        //设置权限
        info.addStringPermission(user.getPerms());
        return info;
    }

    //权限信息认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        Users u=new Users();
        u.setUserName(usernamePasswordToken.getUsername());
        UserVo users=usersService.checkOne(u);
        if(users != null){
            return new SimpleAuthenticationInfo(users,users.getPassword(),users.getUserName());
        }
        return null;

    }
}
